<template>
  <div>
    <el-card hoverable :bordered="false" title="定时任务查询" class="search-card">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <el-form :inline="true" :model="form" size="small" @keyup.enter.native="searchQuery">
          <el-row :gutter="24">
            <el-col :md="6" :sm="10">
              <el-form-item label="任务类名">
                <el-input placeholder="请输入任务类名" v-model="form.jobName" allowClear></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="10">
              <el-form-item label="任务组名">
                <el-input placeholder="请输入任务组名" v-model="form.jobGroup" allowClear></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="10">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <el-button type="primary" @click="searchQuery" icon="search">查询</el-button>
                <el-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</el-button>
              </span>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-card :bordered="false" title="定时任务列表" style="margin-top: 20px;">
      <!-- 操作按钮区域 -->
      <div style="margin-bottom:10px">
        <el-button @click="handleAdd" type="primary" icon="plus">新增</el-button>
      </div>

      <!-- table区域-begin -->
      <div>
        <el-table
          ref="table"
          size="middle"
          bordered
          rowKey="jobId"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="loading"
          :rowSelection="null"
          @change="handleTableChange"
          :scroll="{ x: '220%' }"
        >
          <span slot="jobType" slot-scope="text">
            <span>{{ getJobType(text) }}</span>
          </span>
          <!-- 错失执行策略（1错失周期立即执行 2错失周期执行一次 3下周期执行） -->
          <span slot="misfirePolicy" slot-scope="text">
            <span>{{ getMisfirePolicy(text) }}</span>
          </span>
          <span slot="jobTenantType" slot-scope="text">
            <span>{{ getJobTenantType(text) }}</span>
          </span>
          <span slot="jobStatus" slot-scope="text">
            <span>{{ getJobStatus(text) }}</span>
          </span>
          <span slot="jobExecuteStatus" slot-scope="text">
            <span>{{ getJobExecute(text) }}</span>
          </span>

          <span slot="action" slot-scope="text, record">
            <a
              @click="resumeJob(record.jobId)"
              v-if="record.jobStatus == 0 || record.jobStatus == 1 || record.jobStatus == 3"
              >启动</a
            >
            <a @click="pauseJob(record.jobId)" v-if="record.jobStatus == 2">停止</a>
            <!-- <a-divider type="vertical" />
            <a-popconfirm
              placement="top"
              title="确定删除吗?"
              @confirm="() => handleDel(record.jobId)"
            >
              <a v-if="record.jobStatus != 2">删除</a>
            </a-popconfirm>

            <a-divider v-if="record.jobStatus != 2" type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a v-if="record.jobStatus != 2" @click="handleEdit(record)">编辑</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleDetail(record)">查看</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown> -->
          </span>

          <!-- 状态渲染模板 -->
          <template slot="customRenderStatus" slot-scope="status">
            <a-tag v-if="status == 0" color="green">已启动</a-tag>
            <a-tag v-if="status == -1" color="orange">已暂停</a-tag>
          </template>
        </el-table>
      </div>
      <!-- table区域-end -->
    </el-card>
    <quartzJob-modal ref="QuartzJobModal" @ok="modalFormOk"></quartzJob-modal>
  </div>
</template>

<script>
import QuartzJobModal from './components/QuartzJobModal'
import { getSysJobList, deleteSysJob, startSysJob, shutdownSysJob } from './js/task'

export default {
  name: 'QuartzJobList',
  components: {
    QuartzJobModal
  },
  data () {
    return {
      description: '定时任务在线管理',
      form: {},
      // 查询条件
      queryParam: {},
      // 自定义分页参数为current,size
      customPage: true,
      dataSource: [],
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      pagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      // 表头
      columns: [
        {
          title: '任务类名',
          align: 'center',
          // fixed: 'left',
          dataIndex: 'jobName',
          width: 180
        },
        {
          title: '任务组名',
          align: 'center',
          dataIndex: 'jobGroup',
          width: 180
        },
        {
          title: '执行顺序',
          align: 'center',
          dataIndex: 'jobOrder',
          width: 90
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'jobType',
          scopedSlots: { customRender: 'jobType' },
          width: 120
        },
        {
          title: '调用地址',
          align: 'center',
          dataIndex: 'executePath',
          width: 300
        },
        {
          title: '类路径',
          align: 'center',
          dataIndex: 'className',
          width: 250
        },
        {
          title: '任务方法',
          align: 'center',
          dataIndex: 'methodName',
          width: 200
        },
        {
          title: '参数值',
          align: 'center',
          dataIndex: 'methodParamsValue',
          width: 180
        },
        {
          title: 'cron表达式',
          align: 'center',
          dataIndex: 'cronExpression',
          width: 180
        },
        {
          title: '错失执行策略',
          align: 'center',
          dataIndex: 'misfirePolicy',
          scopedSlots: { customRender: 'misfirePolicy' },
          width: 150
        },
        {
          title: '租户任务类型',
          align: 'center',
          dataIndex: 'jobTenantType',
          scopedSlots: { customRender: 'jobTenantType' },
          width: 150
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'jobStatus',
          scopedSlots: { customRender: 'jobStatus' },
          width: 100
        },
        {
          title: '任务异常',
          align: 'center',
          dataIndex: 'jobExecuteStatus',
          scopedSlots: { customRender: 'jobExecuteStatus' },
          width: 150
        },
        {
          title: '租户id',
          align: 'center',
          dataIndex: 'tenantId',
          width: 100
        },
        {
          title: '备注信息',
          align: 'center',
          dataIndex: 'remark',
          width: 150
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          // fixed: 'right',
          scopedSlots: { customRender: 'action' },
          width: 180
        }
      ]
    }
  },
  computed: {},
  mounted () {
    this.$nextTick(() => {
      this.loadData()
    })
  },
  methods: {
    loadData () {
      this.pageQuery()
    },
    // 分页查询
    pageQuery () {
      // 避免输入后，清空以''查不出问题
      let jobName = !this.queryParam.jobName ? undefined : this.queryParam.jobName
      let jobGroup = !this.queryParam.jobGroup ? undefined : this.queryParam.jobGroup

      const { current, pageSize } = this.pagination
      const params = Object.assign(
        {},
        { current, pageSize },
        this.queryParam,
        { jobName: jobName },
        { jobGroup: jobGroup }
      )

      getSysJobList(params)
        .then(res => {
          if (res.data != null) {
            this.dataSource = res.data.records
            this.pagination.total = res.data.total
          } else {
            this.dataSource = []
            this.pagination.total = 0
          }
        })
        .finally(() => (this.loading = false))
    },

    // 查询
    searchQuery () {
      this.pagination.current = 1
      this.pageQuery()
    },
    // 重置
    searchReset () {
      this.queryParam = {}
    },

    // 分页改变回调
    handleTableChange (pagination) {
      this.pagination = pagination
      this.loadData()
    },
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    // 查看
    handleDetail (record) {
      this.$refs.QuartzJobModal.title = '定时任务详情'
      this.$refs.QuartzJobModal.isAdd = false
      this.$refs.QuartzJobModal.disableSubmit = true
      this.$refs.QuartzJobModal.edit(record)
    },

    // 添加
    handleAdd () {
      this.$refs.QuartzJobModal.title = '新建定时任务'
      this.$refs.QuartzJobModal.isAdd = true
      this.$refs.QuartzJobModal.disable = false
      this.$refs.QuartzJobModal.edit()
    },
    // 修改
    handleEdit: function (record) {
      this.$refs.QuartzJobModal.title = '修改定时定时任务'
      this.$refs.QuartzJobModal.isAdd = false
      this.$refs.QuartzJobModal.disable = true
      this.$refs.QuartzJobModal.edit(record)
    },

    // 删除
    handleDel (id) {
      let that = this
      deleteSysJob(id).then(res => {
        if (res.code === 0) {
          if (this.dataSource.length === 1 && this.pagination.current > 1) {
            this.pagination.current--
          }
          that.$message.success('删除成功')
          that.loadData()
        } else {
          that.$message.warning(res.msg)
        }
      })
    },

    modalFormOk () {
      // 新增/修改 成功时，重载列表
      this.loadData()
    },

    // 暂停定时任务
    pauseJob: function (id) {
      let that = this
      this.$confirm({
        title: '确认暂停',
        content: '是否暂停选中任务?',
        onOk: function () {
          shutdownSysJob(id).then(res => {
            if (res.code === 0) {
              that.$message.success('暂停成功')
              that.loadData()
            } else {
              that.$message.warning(res.msg)
            }
          })
        }
      })
    },

    // 恢复定时任务
    resumeJob (id) {
      let that = this
      this.$confirm({
        title: '确认启动',
        content: '是否启动选中任务?',
        onOk () {
          startSysJob(id).then(res => {
            if (res.code === 0) {
              that.$message.success('启动成功')
              that.loadData()
            } else {
              that.$message.warning(res.msg)
            }
          })
        }
      })
    },

    // 1、java类;2、spring bean名称;3、rest调用;4、jar调用;9其他
    getJobType (value) {
      let status = ''
      switch (value) {
        case '1':
          status = 'java类'
          break
        case '2':
          status = 'spring bean名称'
          break
        case '3':
          status = 'rest调用'
          break
        case '4':
          status = 'jar调用'
          break
        case '9':
          status = '其他'
          break
      }
      return status
    },

    // 错失执行策略（1错失周期立即执行 2错失周期执行一次 3下周期执行
    getMisfirePolicy (value) {
      let status = ''
      switch (value) {
        case '1':
          status = '错失周期立即执行'
          break
        case '2':
          status = '错失周期执行一次'
          break
        case '3':
          status = '下周期执行'
          break
      }
      return status
    },

    // 1、多租户任务;2、非多租户任务
    getJobTenantType (value) {
      let status = ''
      switch (value) {
        case '1':
          status = '多租户任务'
          break
        case '2':
          status = '非多租户任务'
          break
      }
      return status
    },
    // 状态（0、未发布;1、已发布;2、运行中;3、暂停;4、删除;）
    getJobStatus (value) {
      let status = ''
      switch (value) {
        case '0':
          status = '未发布'
          break
        case '1':
          status = '已发布'
          break
        case '2':
          status = '运行中'
          break
        case '3':
          status = '暂停'
          break
        case '4':
          status = '删除'
          break
      }
      return status
    },
    // 状态（0正常 1异常）
    getJobExecute (value) {
      let status = ''
      switch (value) {
        case '0':
          status = '正常'
          break
        case '1':
          status = '异常'
          break
      }
      return status
    }
  }
}
</script>
<style scoped></style>
